﻿using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Microsoft.Office.Interop.Word;
using Microsoft.Win32;
using Project5188.BUS;
using Project5188.BUS.DocumentManagement;
using Project5188.BUS.EducationAndTraining;
using Project5188.BUS.Operations;
using Project5188.BUS.SalesAndCustomerRelations;
using Project5188.Client.ClientCodes;
using VIBlend.WPF.Controls;
using Button = System.Windows.Controls.Button;
using CheckBox = System.Windows.Controls.CheckBox;
using DatePicker = Microsoft.Windows.Controls.DatePicker;
using Image = System.Drawing.Image;
using WORD = Microsoft.Office.Interop.Word;
using System.Runtime.InteropServices;
using Document = Project5188.BUS.DocumentManagement.Document;

namespace Project5188.Client
{
    /// <summary>
    /// Interaction logic for InsertWindow.xaml
    /// </summary>
    public partial class InsertWindow
    {
        private Dictionary<string, resource> _resourceDic;
        private static PropertyInfo[] _propertyInfos;
        private static dynamic _detailEntity;
        private readonly List<string> _numericControls = new List<string>();
        private string _pageName;
        private long _userId;

        public InsertWindow()
        {
            InitializeComponent();

            TransactionInfo.TransactionId = null;
        }

        protected override void OnPreviewTextInput(TextCompositionEventArgs e)
        {
            if (_numericControls.Contains(((FrameworkElement)(e.OriginalSource)).Name))
            {
                e.Handled = !PageBase.AreAllValidNumericChars(e.Text);
            }
            base.OnPreviewTextInput(e);
        }

        public void SetEntity<T>(DetailView<T> detail, string pageName, params long[] parameters)
        {
            if (detail == null) throw new ArgumentNullException("detail");

            _pageName = pageName;
            _resourceDic = BUS.Resources.GetResourceByPageName(pageName);

            detail.Entity = detail.GetEntity();
            _detailEntity = detail;

            _propertyInfos = detail.Entity.GetType().GetProperties();

            foreach (var propertyInfo in _propertyInfos)
            {
                // ReSharper disable PossibleNullReferenceException
                if (!(propertyInfo.PropertyType).FullName.Contains("Data") &&
                    !(propertyInfo.PropertyType).FullName.Contains("Project5188") &&
                    propertyInfo.Name != "IsDeleted" &&
                    propertyInfo.Name != "ModifyBy" &&
                    propertyInfo.Name != "ModifyDate" &&
                    propertyInfo.Name != "CreateBy")
                    // ReSharper restore PossibleNullReferenceException
                {
                    if (propertyInfo.Name != "ID")
                    {
                        if (propertyInfo.Name.Split('_').Length > 1 && propertyInfo.Name.Split('_')[1] == "ID")
                        {
                            continue;
                        }

                        resource resourceKey;
                        _resourceDic.TryGetValue(propertyInfo.Name, out resourceKey);

                        var lblHeader = new Label
                                            {
                                                Name = "lbl" + propertyInfo.Name,
                                                Content =
                                                    resourceKey != null
                                                        ? resourceKey.Value + " : "
                                                        : propertyInfo.Name + " : ",
                                                Height = 23,
                                                HorizontalContentAlignment = HorizontalAlignment.Left
                                            };

                        RegisterName(lblHeader.Name, lblHeader);
                        StackPanel1.Children.Add(lblHeader);

                        var lblEmpty = new Label {Height = 10};
                        StackPanel1.Children.Add(lblEmpty);

                        if (propertyInfo.Name.Contains("ParameterValueID"))
                        {
                            string parameterId = propertyInfo.Name.Split('_')[2];
                            var parameterValues = new ParameterValues();

                            var drpValue = new ComboBox
                                               {
                                                   Name = "drp" + propertyInfo.Name,
                                                   SelectedValuePath = "ID",
                                                   IsSynchronizedWithCurrentItem = true,
                                                   ItemTemplate = Resources["comboTemplate"] as DataTemplate,
                                                   Width = 200,
                                                   Height = 23,
                                                   ItemsSource =
                                                       parameterValues.GetEntityByParameterId(Convert.ToInt64(parameterId)),
                                                   HorizontalAlignment = HorizontalAlignment.Right
                                               };

                            if (pageName == Extensions.PageNames.DocumentPage.ToString())
                            {
                                switch (propertyInfo.Name)
                                {
                                    case "c_DocumentTypeParameterValueID_30":
                                        drpValue.SelectionChanged += DrpValueSelectionChanged;
                                        break;
                                    case "g_DocumentStatusParameterValueID_27":
                                        drpValue.IsEnabled = false;
                                        break;
                                    case "h_FlowTypeParameterValueID_31":
                                        drpValue.IsEnabled = false;
                                        break;
                                    case "i_DocFlowTypeParameterValueID_28":
                                        drpValue.IsEnabled = false;

                                        var cmbBox = (ComboBox)FindName("drpc_DocumentTypeParameterValueID_30");
                                        if (cmbBox == null || Convert.ToInt64(cmbBox.SelectedValue) <= 0) return;

                                        var documentTypeRelations = new DocumentTypeRelation();
                                        drpValue.SelectedValue =
                                            documentTypeRelations.GetEntityByDocumentTypeId(
                                                Convert.ToInt64(cmbBox.SelectedValue))[0].c_IsRequiredApproval
                                                ? 375
                                                : 376;
                                        break;
                                }
                            }

                            RegisterName(drpValue.Name, drpValue);
                            StackPanel2.Children.Add(drpValue);

                            var lblEmpty4 = new Label {Height = 10};
                            StackPanel2.Children.Add(lblEmpty4);
                        }
                        else if ((pageName == Extensions.PageNames.CommunicationInfoPage.ToString() ||
                            pageName == Extensions.PageNames.DinnerExpenseDetailPage.ToString() ||
                            pageName == Extensions.PageNames.DressInfoPage.ToString() ||
                            pageName == Extensions.PageNames.IdCardInfoPage.ToString() ||
                            pageName == Extensions.PageNames.InsuranceInfoPage.ToString() ||
                            pageName == Extensions.PageNames.PersonnelActionPage.ToString() ||
                            pageName == Extensions.PageNames.PersonnelNomineePage.ToString() ||
                            pageName == Extensions.PageNames.PersonnelWorkOutPage.ToString() ||
                            pageName == Extensions.PageNames.PersonnelInspectionPage.ToString()) && 
                            propertyInfo.Name.Split('_').Length > 1 
                            && propertyInfo.Name.Split('_')[1] == "PersonnelID")
                        {
                            var personelInfos = new PersonnelInfos();
                            var drpValue = new ComboBox
                            {
                                Name = "drp" + propertyInfo.Name,
                                SelectedValuePath = "a_ID",
                                IsSynchronizedWithCurrentItem = true,
                                ItemTemplate = Resources["personnelTemplate"] as DataTemplate,
                                Width = 200,
                                Height = 23,
                                ItemsSource =
                                    personelInfos.GetEntityList(),
                                HorizontalAlignment = HorizontalAlignment.Right
                            };

                            if (parameters.Length > 0 && parameters[0] > 0)
                            {
                                drpValue.SelectedValue = parameters[0].ToString();
                            }

                            RegisterName(drpValue.Name, drpValue);
                            StackPanel2.Children.Add(drpValue);

                            var lblEmpty6 = new Label { Height = 10 };
                            StackPanel2.Children.Add(lblEmpty6);
                        }
                        else if ((pageName == Extensions.PageNames.CustomerSalesInfoPage.ToString() ||
                            pageName == Extensions.PageNames.CreateOfferPage.ToString()) && 
                            propertyInfo.Name.Split('_').Length > 1 && 
                            propertyInfo.Name.Split('_')[1] == "CustomerInfoID")
                        {
                            var customerInfos = new CustomerInfos();
                            var drpValue = new ComboBox
                            {
                                Name = "drp" + propertyInfo.Name,
                                SelectedValuePath = "a_ID",
                                IsSynchronizedWithCurrentItem = true,
                                ItemTemplate = Resources["customerTemplate"] as DataTemplate,
                                Width = 200,
                                Height = 23,
                                ItemsSource =
                                    customerInfos.GetEntityList(),
                                HorizontalAlignment = HorizontalAlignment.Right
                            };

                            RegisterName(drpValue.Name, drpValue);
                            StackPanel2.Children.Add(drpValue);

                            var lblEmpty7 = new Label { Height = 10 };
                            StackPanel2.Children.Add(lblEmpty7);
                        }
                        else if ((pageName == Extensions.PageNames.DocumentPage.ToString()) &&
                        propertyInfo.Name.Split('_').Length > 1 &&
                        propertyInfo.Name.Split('_')[1].Contains("UserID"))
                        {
                            var users = new Users();
                            var drpValue = new ComboBox
                            {
                                Name = "drp" + propertyInfo.Name,
                                SelectedValuePath = "ID",
                                IsSynchronizedWithCurrentItem = true,
                                ItemTemplate = Resources["usersTemplate"] as DataTemplate,
                                Width = 200,
                                Height = 23,
                                ItemsSource =
                                    users.GetEntityList(),
                                HorizontalAlignment = HorizontalAlignment.Right
                            };

                            var cmbBox = (ComboBox)FindName("drpi_DocFlowTypeParameterValueID_28");
                            if (cmbBox != null && cmbBox.Items.Count > 0 && Convert.ToInt64(cmbBox.SelectedValue) == 376)
                            {
                                drpValue.SelectedValue = UserInfo.UserId;
                                drpValue.IsEnabled = false;
                            }

                            RegisterName(drpValue.Name, drpValue);
                            StackPanel2.Children.Add(drpValue);

                            var lblEmpty14 = new Label { Height = 10 };
                            StackPanel2.Children.Add(lblEmpty14);
                        }
                        else if ((pageName == Extensions.PageNames.InspectionInfoPage.ToString() ||
                        pageName == Extensions.PageNames.InstitutionInspectionPage.ToString()) &&
                        propertyInfo.Name.Split('_').Length > 1 &&
                        propertyInfo.Name.Split('_')[1] == "InstitutionID")
                        {
                            var institutions = new Institutions();
                            var drpValue = new ComboBox
                            {
                                Name = "drp" + propertyInfo.Name,
                                SelectedValuePath = "a_ID",
                                IsSynchronizedWithCurrentItem = true,
                                ItemTemplate = Resources["institutionTemplate"] as DataTemplate,
                                Width = 200,
                                Height = 23,
                                ItemsSource =
                                    institutions.GetEntityList(),
                                HorizontalAlignment = HorizontalAlignment.Right
                            };

                            RegisterName(drpValue.Name, drpValue);
                            StackPanel2.Children.Add(drpValue);

                            var lblEmpty8 = new Label { Height = 10 };
                            StackPanel2.Children.Add(lblEmpty8);
                        }
                        else if ((pageName == Extensions.PageNames.CoursePage.ToString()) && 
                            propertyInfo.Name.Split('_').Length > 1 && 
                            propertyInfo.Name.Split('_')[1] == "TeacherID")
                        {
                            var teacherRegistries = new TeacherRegistries();
                            // ReSharper disable UseObjectOrCollectionInitializer
                            var drpValue = new ComboBox
                            // ReSharper restore UseObjectOrCollectionInitializer
                            {
                                Name = "drp" + propertyInfo.Name,
                                SelectedValuePath = "a_ID",
                                IsSynchronizedWithCurrentItem = true,
                                ItemTemplate = Resources["teacherRegistryTemplate"] as DataTemplate,
                                Width = 200,
                                Height = 23,
                                ItemsSource =
                                    teacherRegistries.GetEntityList(),
                                HorizontalAlignment = HorizontalAlignment.Right
                            };

                            RegisterName(drpValue.Name, drpValue);
                            StackPanel2.Children.Add(drpValue);

                            var lblEmpty9 = new Label { Height = 10 };
                            StackPanel2.Children.Add(lblEmpty9);
                        }
                        else if ((pageName == Extensions.PageNames.RollCallPage.ToString() ||
                            pageName == Extensions.PageNames.SuccessStatusPage.ToString()) && 
                            propertyInfo.Name.Split('_').Length > 1 &&
                            propertyInfo.Name.Split('_')[1] == "StudentID")
                        {
                            var studentRegistries = new StudentRegistries();
                            // ReSharper disable UseObjectOrCollectionInitializer
                            var drpValue = new ComboBox
                            // ReSharper restore UseObjectOrCollectionInitializer
                            {
                                Name = "drp" + propertyInfo.Name,
                                SelectedValuePath = "a_ID",
                                IsSynchronizedWithCurrentItem = true,
                                ItemTemplate = Resources["studentRegistryTemplate"] as DataTemplate,
                                Width = 200,
                                Height = 23,
                                ItemsSource =
                                    studentRegistries.GetEntityList(),
                                HorizontalAlignment = HorizontalAlignment.Right
                            };

                            RegisterName(drpValue.Name, drpValue);
                            StackPanel2.Children.Add(drpValue);

                            var lblEmpty10 = new Label { Height = 10 };
                            StackPanel2.Children.Add(lblEmpty10);
                        }
                        else if ((pageName == Extensions.PageNames.RollCallPage.ToString()) &&
                            propertyInfo.Name.Split('_').Length > 1 &&
                            propertyInfo.Name.Split('_')[1] == "TimeTableID")
                        {
                            var timeTables = new TimeTables();
                            // ReSharper disable UseObjectOrCollectionInitializer
                            var drpValue = new ComboBox
                            // ReSharper restore UseObjectOrCollectionInitializer
                            {
                                Name = "drp" + propertyInfo.Name,
                                SelectedValuePath = "a_ID",
                                IsSynchronizedWithCurrentItem = true,
                                ItemTemplate = Resources["timeTablesTemplate"] as DataTemplate,
                                Width = 200,
                                Height = 23,
                                ItemsSource =
                                    timeTables.GetEntityList(),
                                HorizontalAlignment = HorizontalAlignment.Right
                            };

                            RegisterName(drpValue.Name, drpValue);
                            StackPanel2.Children.Add(drpValue);

                            var lblEmpty11 = new Label { Height = 10 };
                            StackPanel2.Children.Add(lblEmpty11);
                        }
                        else if ((pageName == Extensions.PageNames.SuccessStatusPage.ToString() ||
                            pageName == Extensions.PageNames.TimeTablePage.ToString()) &&
                            propertyInfo.Name.Split('_').Length > 1 &&
                            propertyInfo.Name.Split('_')[1] == "CourseID")
                        {
                            var courses = new Courses();
                            // ReSharper disable UseObjectOrCollectionInitializer
                            var drpValue = new ComboBox
                            // ReSharper restore UseObjectOrCollectionInitializer
                            {
                                Name = "drp" + propertyInfo.Name,
                                SelectedValuePath = "a_ID",
                                IsSynchronizedWithCurrentItem = true,
                                ItemTemplate = Resources["coursesTemplate"] as DataTemplate,
                                Width = 200,
                                Height = 23,
                                ItemsSource =
                                    courses.GetEntityList(),
                                HorizontalAlignment = HorizontalAlignment.Right
                            };

                            RegisterName(drpValue.Name, drpValue);
                            StackPanel2.Children.Add(drpValue);

                            var lblEmpty12 = new Label { Height = 10 };
                            StackPanel2.Children.Add(lblEmpty12);
                        }
                        else if ((pageName == Extensions.PageNames.UserPage.ToString()) &&
                            propertyInfo.Name == "RoleGroupID")
                        {
                            var roleGroups = new RoleGroups();
                            // ReSharper disable UseObjectOrCollectionInitializer
                            var drpValue = new ComboBox
                            // ReSharper restore UseObjectOrCollectionInitializer
                            {
                                Name = "drp" + propertyInfo.Name,
                                SelectedValuePath = "ID",
                                IsSynchronizedWithCurrentItem = true,
                                ItemTemplate = Resources["roleGroupsTemplate"] as DataTemplate,
                                Width = 200,
                                Height = 23,
                                ItemsSource =
                                    roleGroups.GetEntityList(),
                                HorizontalAlignment = HorizontalAlignment.Right
                            };

                            RegisterName(drpValue.Name, drpValue);
                            StackPanel2.Children.Add(drpValue);

                            var lblEmpty13 = new Label { Height = 10 };
                            StackPanel2.Children.Add(lblEmpty13);
                        }
                        else if ((propertyInfo.Name.Split('_').Length > 1 &&
                                 propertyInfo.Name.Split('_')[1].StartsWith("Is")) ||
                                 propertyInfo.Name.StartsWith("Is"))
                        {
                            var chkValue = new CheckBox
                                               {
                                                   Name = "chk" + propertyInfo.Name,
                                                   HorizontalAlignment = HorizontalAlignment.Right,
                                                   Height = 23
                                               };

                            RegisterName(chkValue.Name, chkValue);
                            StackPanel2.Children.Add(chkValue);

                            var lblEmpty3 = new Label { Height = 10 };
                            StackPanel2.Children.Add(lblEmpty3);
                        }
                        else if (propertyInfo.Name.Contains("Date") && propertyInfo.PropertyType == typeof(DateTime))
                        {
                            var dtValue = new DatePicker
                                              {
                                                  Name = "dt" + propertyInfo.Name,
                                                  Width = 200,
                                                  Height = 23,
                                                  HorizontalAlignment = HorizontalAlignment.Right
                                              };

                            RegisterName(dtValue.Name, dtValue);
                            StackPanel2.Children.Add(dtValue);

                            var lblEmpty4 = new Label { Height = 10 };
                            StackPanel2.Children.Add(lblEmpty4);
                        }
                        else if (propertyInfo.Name.Split('_').Length > 1 &&
                             propertyInfo.Name.Split('_')[1].Contains("ImagePath"))
                        {
                            var imageButton = new Button
                            {
                                Name = "btnAddImage",
                                Content = "...",
                                Height = 23,
                                Width = 40,
                                HorizontalAlignment = HorizontalAlignment.Right
                            };

                            imageButton.Click += ImageButtonClick;

                            StackPanel2.Children.Add(imageButton);

                            var txtValue = new TextBox
                                               {
                                                   Name = "txtImagePath",
                                                   Height = 23,
                                                   Width = 150,
                                                   Margin =
                                                       new Thickness(imageButton.Margin.Left,
                                                                     imageButton.Margin.Top - 23,
                                                                     imageButton.Margin.Right - 210,
                                                                     imageButton.Margin.Bottom),
                                                   IsEnabled = false
                                               };

                            RegisterName(txtValue.Name, txtValue);
                            StackPanel2.Children.Add(txtValue);

                            var lblEmpty2 = new Label { Height = 10 };
                            StackPanel2.Children.Add(lblEmpty2);
                        }
                        else if(propertyInfo.PropertyType == typeof(decimal))
                        {
                            var decimalBox = new NumberEditor
                                                 {
                                                     Name = "dcb" + propertyInfo.Name,
                                                     Height = 23,
                                                     Width = 200,
                                                     HorizontalAlignment = HorizontalAlignment.Right,
                                                     CultureInfo = CultureInfo.InvariantCulture, 
                                                     DecimalPlaces = 2,
                                                     SpinType = SpinType.SpinDigit,
                                                     EnableDefaultValidation = true,
                                                     Maximum = 99999999999,
                                                     Minimum = 0,
                                                     MaxLength = 11
                                                 };

                            decimalBox.ValidationFailed += DecimalBoxValidationFailed;

                            RegisterName(decimalBox.Name, decimalBox);
                            StackPanel2.Children.Add(decimalBox);

                            var lblEmpty2 = new Label { Height = 10 };
                            StackPanel2.Children.Add(lblEmpty2);
                        }
                        else
                        {
                            var txtValue = new TextBox
                                               {
                                                   Name = "txt" + propertyInfo.Name,
                                                   Height = 23,
                                                   Width = 200,
                                                   HorizontalAlignment = HorizontalAlignment.Right
                                               };

                            if (propertyInfo.PropertyType == typeof(string) && 
                                (propertyInfo.Name.Contains("Email") || 
                                propertyInfo.Name.ToLower().Contains("name") ||
                                propertyInfo.Name.Contains("AuthorsOffer") ||
                                propertyInfo.Name.Contains("Section")))
                            {
                                txtValue.MaxLength = 150;
                            }
                            else if (propertyInfo.PropertyType == typeof(string) && 
                                (propertyInfo.Name.Contains("Explanation") || 
                                propertyInfo.Name.Contains("Address") ||
                                propertyInfo.Name.Contains("FirmsEarlierWork") ||
                                propertyInfo.Name.Contains("Detail") ||
                                propertyInfo.Name.Contains("ActionTaken") ||
                                propertyInfo.Name.Contains("CompanyLetterhead") ||
                                propertyInfo.Name.Contains("TextContext") ||
                                propertyInfo.Name.Contains("Value") ||
                                propertyInfo.Name.Contains("ReceivedAward") ||
                                propertyInfo.Name.Contains("WhatAwardGiven") ||
                                propertyInfo.Name.Contains("PenaltyInfo") ||
                                propertyInfo.Name.Contains("Content") ||
                                propertyInfo.Name.Contains("CertificateIssuePath") ||
                                propertyInfo.Name.Contains("Note") ||
                                propertyInfo.Name.Contains("Pass")))
                            {
                                txtValue.MaxLength = 255;
                            }
                            else if (propertyInfo.PropertyType == typeof(string))
                            {
                                txtValue.MaxLength = 50;
                            }
                            else if (propertyInfo.PropertyType == typeof(int))
                            {
                                txtValue.MaxLength = 11;
                            }

                            if (propertyInfo.PropertyType.Name.Contains("Int") && propertyInfo.PropertyType.Name != "Nullable`1")
                            {
                                _numericControls.Add(txtValue.Name);
                            }

                            if (pageName == Extensions.PageNames.ParameterValuePage.ToString())
                            {
                                switch (propertyInfo.Name)
                                {
                                    case "ParameterID":
                                        txtValue.IsEnabled = false;
                                        txtValue.Text = parameters[0].ToString();
                                        break;
                                    case "LanguageCode":
                                        txtValue.Text = "tr-TR";
                                        txtValue.IsEnabled = false;
                                        break;
                                }
                            }

                            if (pageName == Extensions.PageNames.DocumentPage.ToString())
                            {
                                switch (propertyInfo.Name)
                                {
                                    case "d_Version":
                                        txtValue.IsEnabled = false;
                                        txtValue.Text = "1.0";
                                        break;
                                }
                            }

                            RegisterName(txtValue.Name, txtValue);
                            StackPanel2.Children.Add(txtValue);

                            var lblEmpty2 = new Label { Height = 10 };
                            StackPanel2.Children.Add(lblEmpty2);
                        }
                    }
                }
            }

            if (pageName == Extensions.PageNames.DocumentPage.ToString())
            {
                var imageButtonFile = new Button
                {
                    Name = "btnAddFile",
                    Content = "...",
                    Height = 23,
                    Width = 40,
                    HorizontalAlignment = HorizontalAlignment.Right
                };

                imageButtonFile.Click += ImageButtonFileClick;

                StackPanel2.Children.Add(imageButtonFile);

                var txtValue = new TextBox
                {
                    Name = "txtFilePath",
                    Height = 23,
                    Width = 150,
                    Margin =
                        new Thickness(imageButtonFile.Margin.Left,
                                      imageButtonFile.Margin.Top - 23,
                                      imageButtonFile.Margin.Right - 210,
                                      imageButtonFile.Margin.Bottom),
                    IsEnabled = false
                };

                RegisterName(txtValue.Name, txtValue);
                StackPanel2.Children.Add(txtValue);

                var lblEmpty2 = new Label { Height = 10 };
                StackPanel2.Children.Add(lblEmpty2);
            }

            var button = new Button
            {
                Name = "btnAdd",
                Content = "Ekle",
                Margin = new Thickness(2, 2, 2, 2),
                Height = 23,
                Width = 100,
                HorizontalAlignment = HorizontalAlignment.Left
            };

            button.Click += ButtonClick;

            StackPanel2.Children.Add(button);
        }

        void DrpValueSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var cmbBox = (ComboBox)FindName("drpi_DocFlowTypeParameterValueID_28");
            if (cmbBox == null || Convert.ToInt64(cmbBox.SelectedValue) <= 0) return;
            
            var documentTypeRelations = new DocumentTypeRelation();
            cmbBox.SelectedValue = documentTypeRelations.GetEntityByDocumentTypeId(Convert.ToInt64(((ComboBox)sender).SelectedValue))[0].c_IsRequiredApproval ? 375 : 376;

            if (Convert.ToInt64(cmbBox.SelectedValue) == 376)
            {
                var cmbUserBox = (ComboBox)FindName("drpj_ApprovalUserID");
                if (cmbUserBox != null && cmbUserBox.Items.Count > 0)
                {
                    cmbUserBox.SelectedValue = UserInfo.UserId;
                    cmbUserBox.IsEnabled = false;
                }
            }
            else
            {
                var cmbUserBox = (ComboBox)FindName("drpj_ApprovalUserID");
                if (cmbUserBox != null && cmbUserBox.Items.Count > 0)
                {
                    cmbUserBox.IsEnabled = true;
                }
            }
        }

        static void DecimalBoxValidationFailed(object sender, EventArgs e)
        {
            ((NumberEditor) sender).Value = 0;
            MessageBox.Show("Bu alana girebileceğiniz değerin uzunluğu max 11 olabilir!");
        }

        void ButtonClick(object sender, RoutedEventArgs e)
        {
            if (_pageName == Extensions.PageNames.DocumentPage.ToString())
            {
                var cmbBox = (ComboBox) FindName("drpi_DocFlowTypeParameterValueID_28");
                if (cmbBox != null && cmbBox.Items.Count > 0 && Convert.ToInt64(cmbBox.SelectedValue) == 375)
                {
                    var cmbUserBox = (ComboBox) FindName("drpj_ApprovalUserID");
                    if (cmbUserBox != null && cmbUserBox.Items.Count > 0 &&
                        Convert.ToInt64(cmbUserBox.SelectedValue) == UserInfo.UserId)
                    {
                        MessageBox.Show(
                            "Kendi dökümanınızı kendiniz onaylayamazsınız! Başka bir kullanıcı seçmelisiniz.");
                        return;
                    }
                }

                var txtFileBox = (TextBox) FindName("txtFilePath");
                var txtDocumentName = (TextBox) FindName("txtb_DocumentName");
                if (txtFileBox != null && !String.IsNullOrEmpty(txtFileBox.Text) &&
                    txtDocumentName != null && !String.IsNullOrEmpty(txtDocumentName.Text))
                {
                    try
                    {
                        var documents = new Document();
                        var documentNo = documents.GetLastDocumentId();

                        documentNo += 1;

                        var parameterValues = new ParameterValues();
                        var serverPath = parameterValues.GetEntityByParameterId(32)[0].Value;
                        var directoryName = serverPath + "\\" + documentNo + "\\1.0";

                        if (!Directory.Exists(directoryName))
                        {
                            Directory.CreateDirectory(directoryName);
                        }

                        var missing = Type.Missing;

                        _Application word = new WORD.Application();
                        var doc = word.Documents.Open(txtFileBox.Text, ReadOnly: true, Visible: false);
                        doc.Activate();
                        doc.SaveAs(directoryName + "\\" + txtDocumentName.Text);
                        word.Quit(ref missing, ref missing, ref missing);

                        Marshal.ReleaseComObject(word);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Döküman Kaydetme Sırasında Hata Oluştu! \n Hata Detayı:" + ex.Message);
                        return;
                    }
                }
                else
                {
                    MessageBox.Show("Lütfen döküman seçiniz!");
                    return;
                }
            }

            _propertyInfos = _detailEntity.Entity.GetType().GetProperties();

            foreach (var propertyInfo in _propertyInfos)
            {
                if (propertyInfo.Name == "ID" ||
                    propertyInfo.Name.Split('_').Length > 1 && propertyInfo.Name.Split('_')[1] == "ID")
                {
                    continue;
                }

                // ReSharper disable PossibleNullReferenceException
                if (!(propertyInfo.PropertyType).FullName.Contains("Data") &&
                    !(propertyInfo.PropertyType).FullName.Contains("Project5188"))
                    // ReSharper restore PossibleNullReferenceException
                {

                    if (propertyInfo.Name.Contains("ParameterValueID") ||
                        (propertyInfo.Name.Split('_').Length > 1 && propertyInfo.Name.Split('_')[1] == "PersonnelID") ||
                        (propertyInfo.Name.Split('_').Length > 1 && propertyInfo.Name.Split('_')[1] == "CustomerInfoID") ||
                        (propertyInfo.Name.Split('_').Length > 1 && propertyInfo.Name.Split('_')[1] == "InstitutionID") ||
                        (propertyInfo.Name.Split('_').Length > 1 && propertyInfo.Name.Split('_')[1] == "TeacherID") ||
                        (propertyInfo.Name.Split('_').Length > 1 && propertyInfo.Name.Split('_')[1] == "StudentID") ||
                        (propertyInfo.Name.Split('_').Length > 1 && propertyInfo.Name.Split('_')[1] == "TimeTableID") ||
                        (propertyInfo.Name.Split('_').Length > 1 && propertyInfo.Name.Split('_')[1] == "CourseID") ||
                        (propertyInfo.Name == "RoleGroupID") ||
                        (propertyInfo.Name.Split('_').Length > 1 && propertyInfo.Name.Split('_')[1].Contains("UserID")))
                    {
                        var cmbBox = (ComboBox) FindName("drp" + propertyInfo.Name);
                        if (cmbBox != null && Convert.ToInt64(cmbBox.SelectedValue) > 0)
                        {
                            propertyInfo.SetValue(_detailEntity.Entity,
                                                  Extensions.ChangeType(cmbBox.SelectedValue, propertyInfo.PropertyType),
                                                  null);

                            if (propertyInfo.Name.Split('_').Length > 1 &&
                                propertyInfo.Name.Split('_')[1].Contains("UserID"))
                            {
                                _userId = Convert.ToInt64(cmbBox.SelectedValue);
                            }
                        }
                        else
                        {
                            resource resourceKey;
                            _resourceDic.TryGetValue(propertyInfo.Name, out resourceKey);
                            MessageBox.Show(resourceKey.Value + " alanı boş geçilemez!");
                            return;
                        }
                    }
                    else if (propertyInfo.Name == "CreateBy")
                    {
                        propertyInfo.SetValue(_detailEntity.Entity,
                                              Extensions.ChangeType(UserInfo.UserId, propertyInfo.PropertyType), null);
                    }
                    else if (propertyInfo.Name == "ModifyBy")
                    {
                        propertyInfo.SetValue(_detailEntity.Entity,
                                              Extensions.ChangeType(UserInfo.UserName, propertyInfo.PropertyType), null);
                    }
                    else if (propertyInfo.Name == "ModifyDate")
                    {
                        propertyInfo.SetValue(_detailEntity.Entity,
                                              Extensions.ChangeType(DateTime.Now, propertyInfo.PropertyType), null);
                    }
                    else if (propertyInfo.Name == "IsDeleted")
                    {
                        propertyInfo.SetValue(_detailEntity.Entity,
                                              Extensions.ChangeType(false, propertyInfo.PropertyType), null);
                    }
                    else if ((propertyInfo.Name.Split('_').Length > 1 && propertyInfo.Name.Split('_')[1].StartsWith("Is")) ||
                             propertyInfo.Name.StartsWith("Is"))
                    {
                        var chkBox = (CheckBox) FindName("chk" + propertyInfo.Name);
                        if (chkBox != null)
                            propertyInfo.SetValue(_detailEntity.Entity,
                                                  Extensions.ChangeType(chkBox.IsChecked, propertyInfo.PropertyType),
                                                  null);
                    }
                    else if (propertyInfo.Name.Contains("Date") && propertyInfo.PropertyType == typeof (DateTime))
                    {
                        var dtValue = (DatePicker) FindName("dt" + propertyInfo.Name);

                        if (dtValue != null)
                        {
                            propertyInfo.SetValue(_detailEntity.Entity,
                                                  Extensions.ChangeType(
                                                      dtValue.SelectedDate.GetValueOrDefault(DateTime.MinValue),
                                                      propertyInfo.PropertyType),
                                                  null);
                        }
                    }
                    else if (propertyInfo.Name.Split('_').Length > 1 &&
                             propertyInfo.Name.Split('_')[1].Contains("ImagePath"))
                    {
                        var txtImageBox = (TextBox) FindName("txtImagePath");
                        if (txtImageBox != null && !String.IsNullOrEmpty(txtImageBox.Text))
                        {
                            try
                            {
                                // Load image.
                                var image = Image.FromFile(txtImageBox.Text);

                                // Compute thumbnail size.
                                var thumbnailSize = Extensions.GetThumbnailSize(image);

                                // Get thumbnail.
                                var thumbnail = image.GetThumbnailImage(thumbnailSize.Width, thumbnailSize.Height,
                                                                        null, IntPtr.Zero);

                                using (var stream = new MemoryStream())
                                {
                                    thumbnail.Save(stream, ImageFormat.Png);

                                    propertyInfo.SetValue(_detailEntity.Entity,
                                                          Extensions.ChangeType(stream.ToArray(),
                                                                                propertyInfo.PropertyType),
                                                          null);
                                }
                                // Save thumbnail.
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("Resim Kaydetme Sırasında Hata Oluştu! \n Hata Detayı:" + ex.Message);
                                return;
                            }
                        }
                        else
                        {
                            MessageBox.Show("Lütfen personel resmini seçiniz!");
                            return;
                        }
                    }
                    else if (propertyInfo.PropertyType == typeof (decimal))
                    {
                        var decimalBox = (NumberEditor) FindName("dcb" + propertyInfo.Name);
                        if (decimalBox != null)
                        {
                            propertyInfo.SetValue(_detailEntity.Entity,
                                                  Extensions.ChangeType(decimalBox.Value, propertyInfo.PropertyType),
                                                  null);
                        }
                    }
                    else
                    {
                        var txtBox = (TextBox) FindName("txt" + propertyInfo.Name);
                        if (txtBox != null)
                        {
                            if (_numericControls.Contains(txtBox.Name) && String.IsNullOrEmpty(txtBox.Text))
                            {
                                resource resourceKey;
                                _resourceDic.TryGetValue(propertyInfo.Name, out resourceKey);
                                MessageBox.Show(resourceKey.Value + " alanı boş geçilemez!");
                                return;
                            }

                            if (propertyInfo.Name == "b_DocumentName" &&
                                (String.IsNullOrEmpty(txtBox.Text) || String.IsNullOrWhiteSpace(txtBox.Text)))
                            {
                                resource resourceKey;
                                _resourceDic.TryGetValue(propertyInfo.Name, out resourceKey);
                                MessageBox.Show(resourceKey.Value + " alanı boş geçilemez!");
                                return;
                            }

                            if (propertyInfo.Name == "Pass")
                            {
                                txtBox.Text = Extensions.Md5Hashing(txtBox.Text);
                            }

                            propertyInfo.SetValue(_detailEntity.Entity,
                                                  Extensions.ChangeType(txtBox.Text, propertyInfo.PropertyType),
                                                  null);
                        }
                    }
                }
            }

            try
            {
                _detailEntity.Insert();
                TransactionInfo.TransactionId = _detailEntity.TransactionId;
            }
            catch (Exception ex)
            {
                TransactionInfo.TransactionId = null;
                MessageBox.Show("Kayıt Ekleme Sırasında Hata Oluştu! \nHata Detayı : " + ex.Message);
            }

            if (_pageName == Extensions.PageNames.DocumentPage.ToString())
            {
                var documentEntity = (DetailView<document>) _detailEntity;

                var user = new Users();
                var userList = user.GetEntityById(_userId);

                var paramValue = new ParameterValues();
                var paramValueList = paramValue.GetEntityByParameterId(34);

                if (userList != null && userList.Count > 0 &&
                    paramValueList != null && paramValueList.Count > 0)
                {
                    try
                    {
                        Extensions.SendMail(userList[0].Email,
                                            "Döküman Onay Akışı Onay Bildirimi -  Otomatik E-Mail",
                                            String.Format(paramValueList[0].Value, documentEntity.Entity.b_DocumentName,
                                                          documentEntity.Entity.parametervalue.Value,
                                                          documentEntity.Entity.parametervalue3.Value));
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Email Gönderme Sırasında Hata Oluştu! \nHata Detayı : " + ex.Message);
                    }
                }

            }

            Close();
        }

        void ImageButtonFileClick(object sender, RoutedEventArgs e)
        {
            var txtBox = (TextBox)FindName("txtFilePath");

            var openFileDialog1 = new OpenFileDialog
            {
                InitialDirectory = "C:\\",
                Filter =
                    "document files (*.doc)|*.doc",
                FilterIndex = 2,
                RestoreDirectory = true
            };

            var result = openFileDialog1.ShowDialog();

            if (result == true)
            {
                if (txtBox != null)
                {
                    txtBox.Text = openFileDialog1.FileName;
                    txtBox.IsEnabled = false;
                }
            }
        }

        void ImageButtonClick(object sender, RoutedEventArgs e)
        {
            var txtBox = (TextBox)FindName("txtImagePath");

            var openFileDialog1 = new OpenFileDialog
            {
                InitialDirectory = "C:\\",
                Filter =
                    "image files (*.jpg)|*.jpg",
                FilterIndex = 2,
                RestoreDirectory = true
            };

            var result = openFileDialog1.ShowDialog();

            if (result == true)
            {
                if (txtBox != null)
                {
                    txtBox.Text = openFileDialog1.FileName;
                    txtBox.IsEnabled = false;
                }
            }
        }
    }
}
